package com.bridge.client.bridgedynamcclient.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bridge.client.bridgedynamcclient.consts.BridgeStatusEnum;
import com.bridge.client.bridgedynamcclient.consts.BridgeTypeEnum;
import com.bridge.client.bridgedynamcclient.bean.BridgeRecordItem;
import com.bridge.client.bridgedynamcclient.bean.UrlConstant;
import com.bridge.client.bridgedynamcclient.bean.vo.resp.BaseResp;
import com.bridge.client.bridgedynamcclient.bean.vo.resp.BridgeRecordData;
import com.bridge.client.bridgedynamcclient.consts.Const;
import com.bridge.client.bridgedynamcclient.utils.FXMLUtil;
import com.bridge.client.bridgedynamcclient.utils.HttpUtil;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.stage.Modality;

import java.net.URL;
import java.util.*;

public class RecordPageController extends BaseController implements Initializable {


    @FXML
    private TableColumn<?, ?> columnName;

    @FXML
    private TableColumn<?, ?> columnCode;

    @FXML
    private TableColumn<?, ?> columnOperate;

    @FXML
    private TableColumn<?, ?> columnState;

    @FXML
    private TableColumn<?, ?> columnType;
    @FXML
    private TableColumn<?, ?> columnSampleNumType0;

    @FXML
    private TableColumn<?, ?> columnSampleNumType1;
    @FXML
    private TableView<BridgeRecordItem> table;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        System.out.println("controller = " + url);
        initListener();
    }

    private void initListener() {
        initPage();
    }

    private void initPage() {

        ObservableList<BridgeRecordItem> items = FXCollections.observableArrayList(getData());

        table.setItems(items);

        columnName.setCellValueFactory(new PropertyValueFactory<>("bridgeName"));
        columnCode.setCellValueFactory(new PropertyValueFactory<>("bridgeCode"));
        columnType.setCellValueFactory(new PropertyValueFactory<>("bridgeType"));
        columnSampleNumType0.setCellValueFactory(new PropertyValueFactory<>("sampleNumType0"));
        columnSampleNumType1.setCellValueFactory(new PropertyValueFactory<>("sampleNumType1"));
        columnState.setCellValueFactory(new PropertyValueFactory<>("bridgeStatus"));
        columnOperate.setCellValueFactory(new PropertyValueFactory<>("operator"));


    }

    private List<BridgeRecordItem> getData(){
        List<BridgeRecordItem> datas=new ArrayList<>();
        return datas;
    }

    private BridgeRecordItem buildItem(BridgeRecordData.BridgeRecord bridgeRecord ){
        BridgeRecordItem item=new BridgeRecordItem();
        item.setRecordId(bridgeRecord.getRecordId());
        item.setBridgeName(bridgeRecord.getBridgeName());
        item.setBridgeCode(bridgeRecord.getBridgeCode());
        item.setBridgeType(BridgeTypeEnum.getDescByType(bridgeRecord.getBridgeType()));
        item.setSampleNumType0(bridgeRecord.getBridgeMeasureModelNumType0().toString());
        item.setSampleNumType1(bridgeRecord.getBridgeMeasureModelNumType1().toString());
        item.setBridgeStatus(BridgeStatusEnum.getDescByCode(bridgeRecord.getResultStatus()));

        Button btnDelete=new Button("删除");
        Button btnEdit=new Button("编辑");
        Button btnShow=new Button("详情");
        Button btnDo=new Button("提交分析");
        Button btnResult=new Button("查看结果");
        //操作按钮容器
        HBox hBox=new HBox();
        btnDelete.setOnAction(a->{
            //弹框 确认。再调用 删除接口
            Optional<ButtonType> buttonType = FXMLUtil.showWarningInfo("删除提醒", "是否删除当前记录?");
            buttonType.ifPresent(val->{
                if((ButtonType.YES.equals(val))){
                    postDelete(item,bridgeRecord);
                }
            });

        });
        //编辑
        btnEdit.setOnAction(a->{
            //已有结果，弹框 确认。再调用 重置结果的接口
            if(bridgeRecord.getResultStatus().equals(BridgeStatusEnum.FINISH.getCode())){
                Optional<ButtonType> buttonType = FXMLUtil.showWarningInfo("重置分析结果", "编辑桥梁档案信息会删除目前桥梁动力特性分析结果，请确认是否继续？");
                buttonType.ifPresent(val->{
                    if((ButtonType.YES.equals(val))){
                        postResetResult(item,bridgeRecord,hBox,btnDo,btnResult);
                    }
                });
            }else {
                //跳转详情页面---回显数据
                FXMLLoader loader = FXMLUtil.getLoader(getClass(), "bridge-add-main-view.fxml");
                FXMLUtil.loadView(loader);
                BridgeAddMainController controller = loader.getController();
                controller.setConfigByRequestDetail(bridgeRecord,true);
            }


        });
        //查看详情
        btnShow.setOnAction(a->{
            //跳转详情页面---回显数据
            FXMLLoader loader = FXMLUtil.getLoader(getClass(), "bridge-add-main-view.fxml");
            FXMLUtil.loadView(loader);
            BridgeAddMainController controller = loader.getController();
            controller.setConfigByRequestDetail(bridgeRecord,false);
        });

        //进行分析
        btnDo.setOnAction(a->{
            //调用接口 进行数据分析
            postAnalysis(item,bridgeRecord,hBox,btnDo,btnResult);

        });
        //查看分析结果
        btnResult.setOnAction(a->{

            //跳转详情页面---回显数据
            FXMLLoader loader = FXMLUtil.getLoader(getClass(), "bridge-analysis-result-view.fxml");
            FXMLUtil.loadView(loader, Modality.APPLICATION_MODAL,item.getBridgeName());
            BridgeAnalysisResultController controller = loader.getController();
            controller.setConfig(item,bridgeRecord);
        });


        hBox.setSpacing(5);
        //删除，任何状态都展示入口
        hBox.getChildren().add(btnDelete);
        //编辑  任何状态都展示入口
        hBox.getChildren().add(btnEdit);
        //详情，任何状态都展示入口
        hBox.getChildren().add(btnShow);
        //分析入口，只要是未完成的 都展示
        if(BridgeStatusEnum.FINISH.getCode().equals(bridgeRecord.getResultStatus())){
            //已出结果的 展示详情
            hBox.getChildren().add(btnResult);
        }else if(BridgeStatusEnum.SUBMIT.getCode().equals(bridgeRecord.getResultStatus())){
            //提交未出结果的，不做分析按钮
        }else {
            //可做分析的 展示分析按钮
            hBox.getChildren().add(btnDo);
        }

        item.setOperator(hBox);
        return item;
    }

    private void postResetResult(BridgeRecordItem item, BridgeRecordData.BridgeRecord bridgeRecord, HBox hBox, Button btnDo, Button btnResult) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                System.out.println("postResetResult = " + item.getBridgeName());
                Map<String,Object> params=new HashMap<>();
                params.put("recordId",item.getRecordId());

                String postedBody = HttpUtil.postBody(UrlConstant.bridgeResetResult, params, null);
                //返回当前的数据结果，更新数据
                BaseResp<Void> baseResp = JSON.parseObject(postedBody, new TypeReference<BaseResp<Void>>() {});

                if(baseResp==null||!baseResp.isSuccess()){
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            FXMLUtil.showAlertInfo(Objects.nonNull(baseResp)?baseResp.getMessage():"请求失败，请重试");
                        }
                    });
                    return;
                }
                System.out.println("postResetResult = 请求数据成功，结果：result:" +JSON.toJSONString(baseResp) );
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        //更新成待分析状态
                        item.setBridgeStatus(BridgeStatusEnum.getDescByCode(0));
                        //更新 数据记录结果
                        bridgeRecord.setResultStatus(0);
                        bridgeRecord.setResultJson(null);
                        bridgeRecord.setImages(null);
                        //处理操作按钮
                        hBox.getChildren().remove(btnResult);
                        hBox.getChildren().add(btnDo);

                        //跳转详情页
                        //跳转详情页面---回显数据
                        FXMLLoader loader = FXMLUtil.getLoader(getClass(), "bridge-add-main-view.fxml");
                        FXMLUtil.loadView(loader);
                        BridgeAddMainController controller = loader.getController();
                        controller.setConfigByRequestDetail(bridgeRecord,true);
                    }
                });
            }
        }).start();
    }

    private void postAnalysis(BridgeRecordItem item, BridgeRecordData.BridgeRecord bridgeRecord, HBox hBox, Button btnDo, Button btnResult) {
        showLoading();
        new Thread(new Runnable() {
            @Override
            public void run() {

                System.out.println("postAnalysis = " + item.getBridgeName());
                Map<String,Object> params=new HashMap<>();
                params.put("recordId",item.getRecordId());

                String postedBody = HttpUtil.postBody(UrlConstant.bridgeAnalysis, params, null);
                //返回当前的数据结果，更新数据
                BaseResp<BridgeRecordData.BridgeRecord> baseResp = JSON.parseObject(postedBody, new TypeReference<BaseResp<BridgeRecordData.BridgeRecord>>() {});

                if(baseResp==null||!baseResp.isSuccess()){

                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            dismissLoading();
                            FXMLUtil.showAlertInfo(Objects.nonNull(baseResp)?baseResp.getMessage():"请求失败，请重试");
                        }
                    });
                    return;
                }
                System.out.println("postAnalysis = 请求数据成功，结果：result:" +JSON.toJSONString(baseResp) );
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        BridgeRecordData.BridgeRecord data = baseResp.getData();
                        item.setBridgeStatus(BridgeStatusEnum.getDescByCode(data.getResultStatus()));

                        bridgeRecord.setResultStatus(data.getResultStatus());
                        bridgeRecord.setResultJson(data.getResultJson());
                        bridgeRecord.setImages(data.getImages());

                        hBox.getChildren().remove(btnDo);
                        hBox.getChildren().add(btnResult);
                        dismissLoading();
                        FXMLUtil.showAlertInfo("分析结果已完成");
                    }
                });
            }
        }).start();

    }


    private void postDelete(BridgeRecordItem item, BridgeRecordData.BridgeRecord bridgeRecord) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                System.out.println("postDelete = " + item.getBridgeName());
                Map<String,Object> params=new HashMap<>();
                params.put("recordId",item.getRecordId());

                String postedBody = HttpUtil.postBody(UrlConstant.bridgeDelete, params, null);
                //返回当前的数据结果，更新数据
                BaseResp<Void> baseResp = JSON.parseObject(postedBody, new TypeReference<BaseResp<Void>>() {});

                if(baseResp==null||!baseResp.isSuccess()){

                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            FXMLUtil.showAlertInfo(Objects.nonNull(baseResp)?baseResp.getMessage():"请求失败，请重试");
                        }
                    });
                    return;
                }
                System.out.println("postDelete = 请求数据成功，结果：result:" +JSON.toJSONString(baseResp) );
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        table.getItems().remove(item);
                        FXMLUtil.showAlertInfo("删除成功");
                    }
                });
            }
        }).start();

    }


    //当前分页
    public void setConfig(Integer pageIndex,Long firstRecordId,BridgeRecordListController bridgeRecordListController) {
       new Thread(new Runnable() {
           @Override
           public void run() {

               System.out.println("setPageIndex = " + pageIndex);
               Map<String,Object> params=new HashMap<>();
               params.put("pageNum",pageIndex+1);
               params.put("pageSize", Const.pageSize);
               params.put("firstRecordId",firstRecordId);

               String postedBody = HttpUtil.postBody(UrlConstant.bridgeListByPage, params, null);
               BaseResp<BridgeRecordData> baseResp = JSON.parseObject(postedBody, new TypeReference<BaseResp<BridgeRecordData>>() {
               });

               if(baseResp==null||!baseResp.isSuccess()){
                   System.out.println("setConfig = 请求数据失败，参数：param:" +params.toString() );
                   Platform.runLater(new Runnable() {
                       @Override
                       public void run() {
                           FXMLUtil.showAlertInfo(Objects.nonNull(baseResp)?baseResp.getMessage():"数据加载失败，请重试");
                       }
                   });

                   return;
               }
               System.out.println("setConfig = 请求数据成功，结果：result:" +JSON.toJSONString(baseResp) );
               BridgeRecordData data = baseResp.getData();
               Platform.runLater(new Runnable() {
                   @Override
                   public void run() {
                       if(pageIndex==0){
                           bridgeRecordListController.callbackFirstPage(data.getBodyList().isEmpty()?null:data.getBodyList().get(0).getRecordId(),data.getTotalSize());
                       }

                       //格式化页面数据
                       if(!data.getBodyList().isEmpty()){
                           for (BridgeRecordData.BridgeRecord bridgeRecord : data.getBodyList()) {
                               table.getItems().add( buildItem(bridgeRecord));
                           }
                       }
                   }
               });


           }
       }).start();

    }


}
